package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.FxyFinancialVoucherTemplateDetails;
import com.ruoyi.system.domain.reqvo.Params;
import com.ruoyi.system.domain.reqvo.VoucherReqVO;
import com.ruoyi.system.mapper.FxyFinancialVoucherTemplateDetailsMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.FxyFinancialVoucherMapper;
import com.ruoyi.system.domain.FxyFinancialVoucher;
import com.ruoyi.system.service.IFxyFinancialVoucherService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 凭证Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-13
 */
@Service
@Transactional
public class FxyFinancialVoucherServiceImpl implements IFxyFinancialVoucherService {
    @Autowired
    private FxyFinancialVoucherMapper fxyFinancialVoucherMapper;

    @Autowired
    private FxyFinancialVoucherTemplateDetailsMapper detailsMapper;

    /**
     * 查询凭证
     *
     * @param id 凭证主键
     * @return 凭证
     */
    @Override
    public FxyFinancialVoucher selectFxyFinancialVoucherById(Integer id) {
        return fxyFinancialVoucherMapper.selectFxyFinancialVoucherById(id);
    }

    /**
     * 查询凭证列表
     *
     * @param fxyFinancialVoucher 凭证
     * @return 凭证
     */
    @Override
    public List<FxyFinancialVoucher> selectFxyFinancialVoucherList(Params params) {

        List<FxyFinancialVoucher> fxyFinancialVouchers = fxyFinancialVoucherMapper.selectFxyFinancialVoucherList(params);


        return fxyFinancialVouchers;
    }

    /**
     * 新增凭证
     *
     * @param fxyFinancialVoucher 凭证
     * @return 结果
     */
    @Override
    public int insertFxyFinancialVoucher(FxyFinancialVoucher fxyFinancialVoucher) {
        int i = fxyFinancialVoucherMapper.insertFxyFinancialVoucher(fxyFinancialVoucher);
        return fxyFinancialVoucher.getId();
    }

    /**
     * 修改凭证
     *
     * @param fxyFinancialVoucher 凭证
     * @return 结果
     */
    @Override
    public int updateFxyFinancialVoucher(FxyFinancialVoucher fxyFinancialVoucher) {
        return fxyFinancialVoucherMapper.updateFxyFinancialVoucher(fxyFinancialVoucher);
    }

    /**
     * 批量删除凭证
     *
     * @param ids 需要删除的凭证主键
     * @return 结果
     */
    @Override
    public int deleteFxyFinancialVoucherByIds(Integer[] ids) {
        return fxyFinancialVoucherMapper.deleteFxyFinancialVoucherByIds(ids);
    }

    /**
     * 删除凭证信息
     *
     * @param id 凭证主键
     * @return 结果
     */
    @Override
    public int deleteFxyFinancialVoucherById(Long id) {
        return fxyFinancialVoucherMapper.deleteFxyFinancialVoucherById(id);
    }

    @Override
    public AjaxResult insertVoucherList(VoucherReqVO voucherReqVO) throws JsonProcessingException {



        List<FxyFinancialVoucherTemplateDetails> detailsArrayList = new ArrayList<>();
        List<FxyFinancialVoucherTemplateDetails> submitArray = voucherReqVO.getSubmitArray();


        Long userId = SecurityUtils.getUserId();
        FxyFinancialVoucher fxyFinancialVoucher = new FxyFinancialVoucher();
        BeanUtils.copyProperties(voucherReqVO, fxyFinancialVoucher);
        ObjectMapper objectMapper = new ObjectMapper();

        fxyFinancialVoucher.setCode(Long.valueOf(voucherReqVO.getCode()));
        fxyFinancialVoucher.setReceiptNum(1L);
        fxyFinancialVoucher.setCreateMember(userId);
        String json = objectMapper.writeValueAsString(submitArray);
        fxyFinancialVoucher.setBillList(json);
        Date voucherDate = fxyFinancialVoucher.getVoucherDate();
        LocalDate localDate = voucherDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();

        fxyFinancialVoucher.setVoucherYear((long) year);
        fxyFinancialVoucher.setVoucherMonth((long) month);
        fxyFinancialVoucher.setAccountSetsId(Long.valueOf(voucherReqVO.getAccountSetsId()));

        fxyFinancialVoucherMapper.insertFxyFinancialVoucher(fxyFinancialVoucher);

        for (FxyFinancialVoucherTemplateDetails fxyFinancialVoucherTemplateDetails : submitArray) {
            FxyFinancialVoucherTemplateDetails details = new FxyFinancialVoucherTemplateDetails();
            BeanUtils.copyProperties(fxyFinancialVoucherTemplateDetails, details);
            details.setVoucherTemplateId(1L);
            details.setVoucherId(fxyFinancialVoucher.getId());
            details.setAccountSetsId(Long.valueOf(voucherReqVO.getAccountSetsId()));
            detailsArrayList.add(details);
        }
        Integer a = detailsMapper.insertBatch(detailsArrayList);


        return AjaxResult.success();
    }

    @Override
    public int examine(Params params) {
        int a = fxyFinancialVoucherMapper.examine(params);

        return a;
    }

    @Override
    public int ReExamine(Integer[] ids) {
        int a = fxyFinancialVoucherMapper.ReExamine(ids);

        return a;
    }

    @Override
    public int Cancellation(Integer[] ids) {
        int a = fxyFinancialVoucherMapper.Cancellation(ids);
        return a;
    }

    @Override
    public int renew(Integer[] ids) {
        int a = fxyFinancialVoucherMapper.renew(ids);
        return a;
    }

    @Override
    public AjaxResult selectVoucherById(Params params) throws JsonProcessingException {

        if (Objects.isNull(params)){
            return AjaxResult.error("参数为空");
        }
        FxyFinancialVoucher fxyFinancialVoucher = fxyFinancialVoucherMapper.selectFxyFinancialVoucherById(params.getId());
        fxyFinancialVoucher.setVoucherDate(params.getVoucherDate());
        if (fxyFinancialVoucher == null) {
            return AjaxResult.error("未找到对应的财务凭证");
        }
        ObjectMapper objectMapper = new ObjectMapper();

        String billList = fxyFinancialVoucher.getBillList();
        List<FxyFinancialVoucherTemplateDetails> list = objectMapper.readValue(billList,
                new TypeReference<List<FxyFinancialVoucherTemplateDetails>>() {
                });

        for (FxyFinancialVoucherTemplateDetails details : list) {
            BigDecimal creditAmount = details.getCreditAmount();
            BigDecimal debitAmount = details.getDebitAmount();

            // 将贷方金额和借方金额都取反
            if (creditAmount != null) {
                details.setCreditAmount(creditAmount.negate());
            }
            if (debitAmount != null) {
                details.setDebitAmount(debitAmount.negate());
            }

            String summary = details.getSummary();
            if (summary.contains("冲销")) {
                return AjaxResult.error("已经冲销过了");
            }

            details.setSummary("冲销" + summary);

        }
        String json = objectMapper.writeValueAsString(list);

        fxyFinancialVoucher.setBillList(json);

        int i = fxyFinancialVoucherMapper.updateFxyFinancialVoucher(fxyFinancialVoucher);

        return i > 0 ? AjaxResult.success() : AjaxResult.error();


    }
}
